<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Category_private extends wsFrontend
{
    public function __construct()
    {
        parent::__construct();
        if (strpos(strtolower($this->uri->uri_string()), 'category_private') !== false) {
            redirect(base_url());
        }
        $this->db->cache_set_path(dirname($this->db->cachedir) . '/category_page/');
    }

    public function index()
    {
        $data = array();
        $this->tpl->meta ['title'] = $this->metadata->get_metadata('_category_index_home_title', 'category_page');
        $this->tpl->meta ['description'] = $this->metadata->get_metadata('_category_index_home_description', 'category_page');
        $this->tpl->meta ['keywords'] = $this->metadata->get_metadata('_category_index_home_keywords', 'category_page');


        $this->load->model('category_model');

        $data['categories'] = $this->category_model->get_parent_categories();

        $this->tpl->breadcrumbs['壁纸分类'] = 'active';

        $this->tpl->contents [] = $this->tpl->fetch('contents/category_page_index', $data);
        $this->tpl->render('layouts/home');
    }

    public function selected($slug = '')
    {
        $slug = rawurldecode($slug);
        $data = array();
        $this->load->model(array('category_model', 'wallpaper_model'));
        $data['category'] = $this->category_model->get_categoryBYCFullSlug($slug);
        if (!$data['category'])
            custom_404();

        $data['search_replace'] = array(
            '{C_SLUG_FULL}' => $data['category']->cFullSlug,
            '{C_SLUG}' => $data['category']->category_slug,
        );

        $data['url'] = $this->route_links->build_link('category_page', $data['search_replace']);
        if ($data['url'] != current_url())
            redirect($data['url'] . $this->frontend_helper->get_query_string());


        $this->tpl->active_category = explode('/', $data['category']->cFullSlug);

        $filter['show_disabled'] = FALSE;
        $filter['per_page'] = $config['per_page'] = $this->config->item('items_per_page');
        $page_number = (int)$this->input->get('page');
        $filter['offset'] = ($page_number ? ($page_number - 1) * $config['per_page'] : 0);
        $filter['bypath'] = true;
        $filter['category'] = $data['category']->category_seq_id;

        $SearchReplace = $this->generate_metadata($data['category']->cFullName, $data['category']->category_name);

        if ($this->input->get('feed') == 'rss') {
            $this->load->helper('xml');
            $feed_data = array();
            $feed_data['title'] = $this->metadata->get_metadata('_category_index_title', 'category_page', $SearchReplace);
            $feed_data['description'] = $this->metadata->get_metadata('_category_index_description', 'category_page', $SearchReplace);
            $feed_data['posts'] = $this->wallpaper_model->getWallpapers($filter + array('rss' => true));
            header("Content-Type: application/rss+xml");
            echo clean_data($this->tpl->fetch('contents/rss', $feed_data));
            exit;
        }

        if (isset($_GET['sort']))
            $filter['sort'] = $_GET['sort'];

        if (isset($_GET['time']))
            $filter['time'] = $_GET['time'];

        $data['total_count'] = $this->wallpaper_model->getWallpapers($filter + array('count' => true));

        //Initialize Pagination
        $config['base_url'] = $data['url'];
        $config['total_rows'] = $data['total_count'];
        $config['custom_query_string'] = TRUE;
        $config['page_query_string'] = TRUE;
        $config['query_string_segment'] = 'page';

        if (!empty($_GET)) {
            $get_method = $this->frontend_helper->get_query_string(array('page'));
            $config['prefix'] = ($get_method ? $get_method . '&' : '?') . 'page=';
            $config['first_url'] = $config['base_url'] . $get_method;
        } else {
            $config['prefix'] = '?page=';
        }

        $this->load->library('pagination');
        $this->pagination->initialize($config);
        $data['pagination'] = $this->pagination->create_links();
        $data['wallpapers'] = $this->wallpaper_model->getWallpapers($filter);

        $cFullSlug = explode('/', $data['category']->cFullSlug);
        $cFullName = explode('|', $data['category']->cFullName);
        $appendSlug = '';

        $this->tpl->breadcrumbs['壁纸分类'] = base_url($this->route_links->get('category_page_index'));

        foreach ($cFullSlug as $k => $cSlug) {
            if ($appendSlug)
                $appendSlug .= '/';
            $category_slug_build = $this->route_links->build_link('category_page', array(
                '{C_SLUG_FULL}' => $appendSlug . $cSlug
            ));
            $this->tpl->breadcrumbs[(isset($cFullName[$k]) ? $cFullName[$k] : $k)] = (count($cFullSlug) - 1 == $k ? 'active' : $category_slug_build);
            $appendSlug .= $cSlug;
        }


        $this->tpl->meta ['title'] = $this->metadata->get_metadata('_category_index_title', 'category_page', $SearchReplace, false, $page_number);
        $this->tpl->meta ['description'] = $this->metadata->get_metadata('_category_index_description', 'category_page', $SearchReplace, false, $page_number);
        $this->tpl->meta ['keywords'] = $this->metadata->get_metadata('_category_index_keywords', 'category_page', $SearchReplace, false, $page_number);

        $this->tpl->contents [] = $this->tpl->fetch('contents/category_page', $data);
        $this->tpl->render('layouts/home');
    }


    private function generate_metadata($path, $category_name)
    {
        $path = array_reverse(explode('|', $path));
        array_shift($path);
        $cat_path = $this->metadata->get_value('_category_index_title', 'category_page');;
        preg_match_all('/\{CAT_PARENTS\}\[([^\]]+)?\]\[([^\]]+?)?\]\[([^\]]+?)?\]/im', $cat_path, $cat_path_result);
        $cat_path_data = '';
        if (!empty($path)) {
            if (isset($cat_path_result[1][0]) && $cat_path_result[1][0]) {
                $cat_path_data .= ' ' . $cat_path_result[1][0] . ' ';
            }
            $cat_path_data .= join(' ' . (isset($cat_path_result[3][0]) ? htmlentities($cat_path_result[3][0]) : '&gt;') . ' ', $path);
            if (isset($cat_path_result[2][0]) && $cat_path_result[2][0]) {
                $cat_path_data .= ' ' . $cat_path_result[2][0] . ' ';
            }
        }
        return array(
            '{CAT_NAME}' => $category_name,
            '\{CAT_PARENTS\}\[([^\]]+)?\]\[([^\]]+?)?\]\[([^\]]+?)?\]' => $cat_path_data,
        );
    }
}
